<template>
  <basePage :show-tabbar="false" :page-params="pageParams" @testAgainFn="testAgainFn">
    <view class="order-payment-con">
      <!-- 从智慧屏进入不展示tab切换 -->
      <u-sticky v-if="!isFromTouchScreen" bg-color="#fff">
        <TopTabs
          key-name="name"
          :list-data="topTabs.list"
          :current="topTabs.current"
          @tabClick="handleSwitchPackWay"
        />
      </u-sticky>
      <address-bar
        v-if="isLogistics"
        :show-default-icon="true"
        :show-right-icon="true"
        :address-data="shippingAddressModel"
        :address-list="shoppingAddList"
        @editAddressFn="editAddressFn"
      />
      <view v-show="!isLogistics" class="list-bg list-group-row">
        <view class="list-title">自提信息</view>
        <view class="group-info">
          <template v-if="isShowMap">
            <!-- #ifdef MP-WEIXIN -->
            <view class="map-box">
              <ViewMap :location="ztInfo.location" :markers-points="markersPoints" @click-map="handleViewMap" />
            </view>
            <!-- #endif -->
            <!-- #ifdef MP-ALIPAY -->
            <view @click.native="handleViewMap">
              <ViewMap :location="ztInfo.location" :markers-points="markersPoints" />
            </view>
            <!-- #endif -->
          </template>
          <MenuCell
            :cell-data.sync="ztInfo"
            :cell-column="ztCellColumn"
            @handelCellMethod="handelCellMethod"
          />
        </view>
      </view>
      <view class="list-sku list-bg">
        <YcProductItem
          :editor-status="false"
          :order-items-detail-data.sync="orderData.products"
          :total-record="totalRecord"
          :all-goods-page-path="'/goodsPages/yc_orderAllgoods'"
          :cannot-view-details="true"
        />
      </view>
      <view class="list-bg list-paymethod">
        <view class="online-payment " :class="isClick=='1001'?'online-payment-curr':''" @click="changePayment('1001')">
          <!-- 图标 -->
          <text class="font_family icon-zaixianzhifu_tongyong_1" />
          <text class="nav">在线支付</text>
          <text class="hint">微信支付支,付宝支付,快捷支付</text>
        </view>
        <view class="online-payment" :class="isClick=='1301'?'online-payment-curr':''" @click="changePayment('1301')">
          <!-- 图标 -->
          <text class="font_family icon-zhangqizhifu_tongyong_1" />
          <text class="nav">对公转账</text>
          <text class="hint">转账后联系客服发送银行回单</text>
        </view>
      </view>
      <view class="list-bg list-group-row">
        <view class="list-title">订单信息</view>
        <view class="group-info">
          <MenuCell
            :cell-data.sync="orderInfo"
            :cell-column="orderCellColumn"
            @handelCellMethod="handelCellMethod"
          />
        </view>
      </view>
      <view class="list-bg list-group-row">
        <view class="list-title">价格明细</view>
        <view class="group-info">
          <MenuCell
            :cell-data.sync="priceInfo"
            :cell-column="priceCellColumn"
            @handelCellMethod="handelCellMethod"
          />
        </view>
      </view>
      <view class="sticky-bottom">
        <view class="order-price">
          订单金额：<text class="price">¥ {{ priceInfo.payTotalMoney || priceInfo.payTotalMoney == 0 ? priceInfo.payTotalMoney : '' }}</text>
        </view>
        <button
          class="sticky-btn btn-orange"
          :plain="true"
          @click="$u.throttle(submitOrderFn, 500)"
        >
          提交订单
        </button>
      </view>
    </view>
    <u-popup
      :show="popShow"
      :close-on-click-overlay="true"
      mode="bottom"
      :safe-area-inset-bottom="true"
      round="16"
      style="pointer-events: auto;"
      @close="close"
    >
      <deliver-way
        v-if="popContent=='deliverWay'"
        :list-data="listData"
        :order-info.sync="orderInfo"
        :order-data.sync="orderData"
        :cur-deliver-way.sync="curDeliverWay"
        :freight="priceInfo.freight"
        :deliver-time-selected.sync="deliverTimeSelected"
        :deliver-time-list.sync="deliverTimeList"
        :set-deliver-way-fn="setDeliverWayFn"
        @click="close"
        @closePopFn="close"
        @showPopFn="showPopFn"
        @selectFn="deliverWayChangeFn"
        @initDataTime="initDataTime"
      />

      <!-- 配送方式 -->
      <selectStore
        v-if="popContent=='selectStore'"
        :order-info.sync="orderInfo"
        :order-data.sync="orderData"
        :cur-deliver-way.sync="curDeliverWay"
        :self-address-model-obj.sync="selfAddressModelObj"
        @click="close"
        @closePopFn="close"
        @backPageFn="showPopFn"
        @selectFn="selfAddressSelectFn"
      />
      <selectSelfDeliveryTime
        v-if="popContent=='selectSelfDeliveryTime'"
        :self-address-model-obj.sync="selfAddressModelObj"
        :self-pickup-time-info="selfPickupTimeInfo"
        :self-take-time="ztInfo.selfTakeTime"
        @click="close"
        @closePopFn="close"
        @backPageFn="showPopFn"
        @updateZtTime="updateZtTime"
      />
      <invoice
        v-if="popContent=='invoice'"
        ref="invoice"
        :order-info.sync="orderInfo"
        :submit-invoice-info.sync="submitInvoiceInfo"
        @click="close"
        @closePopFn="close"
      />
      <needQualification
        v-if="popContent=='needQualification'"
        :order-info.sync="orderInfo"
        @click="close"
        @closePopFn="close"
        @closeFication="closeFication"
      />
      <sendType
        v-if="popContent=='sendType'"
        :order-info.sync="orderInfo"
        @click="close"
        @closePopFn="close"
      />
      <remarks
        v-if="popContent=='remarks'"
        :order-info.sync="orderInfo"
        @click="close"
        @closePopFn="close"
      />
    </u-popup>
    <freight
      :freight-flag.sync="freightFlag"
      :radio-val="priceInfo.freightType"
      @freightFn="freightFn"
    />
    <coupon
      v-if="priceInfo.couponSpuSkuBoList && priceInfo.couponSpuSkuBoList.length > 0"
      :coupon-flag.sync="couponFlag"
      :coupons-list="priceInfo.couponSpuSkuBoList"
      :default-coupon.sync="priceInfo.couponChoosen"
      @selectFn="couponChangeFn"
    />
    <ConfirmModal
      :show="modalOptions.modalShow"
      :modal-list="modalOptions.modalList"
      :custom="modalOptions.custom"
      @confirm="modalConfirmFn"
      @cancel="modalCancelFn"
    />
  </basePage>
</template>

<script>
/**
 确认订单、提交订单、自提库存等商品异常的管理类
 61 外部：商品信息异常：商品信息异常
 前台处理规则：70，75按照价格变更处理，其余为无货
 内部：abnormalProducts code
 70 商品信息异常：商品价格变化。可下单
 71 商品信息异常：商品已下架，无法下单
 72 商品信息异常：商品无可超卖库存，无法下单
 73 商品信息异常：商品信息不全，无法下单（比如重量 体积 价格信息等）
 74 商品信息异常：商品不在该区域售卖，无法下单
 75 商品信息异常：商品促销信息变化，请刷新后重试，可下单
 76 商品信息异常：商品自提库存不足，无法下单
 78 商品信息异常：商品自提时门店库存无货，中心仓库存有货，无法当天自提，可以第二天自提
 79 购买数量不满足当前区域最小起订量
 80 商品信息异常：商品小数位不一致
 81 商品信息异常：临采商品被禁用，无法下单
 90 商品信息异常：询价商品状态不等于已报价或已下单

 1001:在线支付；1101：货到付款；1102：货到付款(现金)；1103： 货到付款(POS机刷卡)；1201：账期支付；1301：线下汇款；1401：银行汇票
 */
import basePage from '@/components/base-page'
import ConfirmModal from '@/components/confirm-modal'
import YcProductItem from '@/components/yc-product-list/yc-product-item'
import AddressBar from '@/components/ycAddressBar/address-bar'
import MenuCell from '@/components/menu-cell'
import { setPageParamsFn } from '@/common/common'
import deliverWay from '@/ycPayments/deliverWay'
import selectStore from '@/ycPayments/selectStore'
import selectSelfDeliveryTime from '@/ycPayments/selectSelfDeliveryTime'
import invoice from '@/ycPayments/invoice'
import needQualification from '@/ycPayments/needQualification'
import sendType from '@/ycPayments/sendType'
import remarks from '../remarks/index'
import freight from '../freight/index'
import coupon from '../coupon/index'
import TopTabs from '@/components/top-tabs'
import ViewMap from '@/components/view-map/map'
import {
  settleOrder,
  preSettleOrder,
  submitOrder,
  joinPromotion,
  getPostTime,
  getSelfPickupTime,
} from '@/api/yc_payment'
import {
  checkMemeberStatusFn,
} from '@/common/common'
import { getShoppingCartList } from '@/api/yc_shoppingCar';
import { ZT_CELL_COLUMN, ORDER_CELL_COLUMN, PRICE_CELL_COLUMN } from './constants'
import qs from '@/lib/qs'
import UText from '../../uni_modules/uview-ui/components/u--text/u--text.vue'
export default {
  name: 'OrderConfirm',
  components: {
    basePage,
    YcProductItem,
    AddressBar,
    MenuCell,
    deliverWay,
    selectStore,
    selectSelfDeliveryTime,
    invoice,
    needQualification,
    sendType,
    freight,
    remarks,
    coupon,
    ConfirmModal,
    TopTabs,
    ViewMap,
    UText
  },
  props: {
    orderDetailData: {
      type: Object,
      default: null
    },
    totalRecord: {
      type: Number,
      default: 0
    },
    showWarehouseLabel: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      popShow: false,
      modalOptions: {
        modalShow: false,
        modalList: [],
        custom: {
          title: '',
          showCancelButton: true,
          showConfirmButton: false,
          confirmText: '仅购买有货商品',
          cancelText: '返回',
          cancelOperation: 'backPurchaseOrder',
          continueBuyingHandleType: '',
        }
      },
      curDeliverWay: '', // 当前选择的配送方式，并不代表最终入参
      popContent: '', // 弹框类型 ['payName','deliverWay', 'sendType', 'invoice', 'needQualification', 'remarks', 'selectStore','selectSelfDeliveryTime']
      pageParams: {
        // state: 'ERROR',
        emptyTitle: '信号可能跑到外星球了哦～',
        errorTitle: '请求失败',
        showButton: true
      },
      ztInfo: {}, // 自提信息（cell data）
      ztCellColumn: [...ZT_CELL_COLUMN],
      orderCellColumn: [...ORDER_CELL_COLUMN],
      priceCellColumn: [...PRICE_CELL_COLUMN],
      // abnormalProducts: [], // 异常商品列表
      abnormalObj: {}, // 异常商品分类集合
      shippingAddressModel: {}, //收货地址
      shoppingAddList: {}, //收货地址列表
      selfAddressModelObj: null, //自提地址
      selfPickupTimeInfo: null, // 自提时间信息
      orderData: {},
      orderInfo: {}, // 订单信息
      tempDeliveryWay: '',
      priceInfo: {}, // 价格信息
      submitInvoiceInfo: {
        invoice: {},
      }, // 发票信息
      deliverTimeSelected: null, //选中的配送时间
      deliverTimeList: [], //配送时间选择列表数据
      shoppingCartList: [],
      settleParams: {

      },
      isVerifyInventory: false, // 获取完结算单后是否校验库存
      freightFlag: false,
      couponFlag: false,
      topTabs: {
        list: [ // 提取方式
          { key: 'logistics', name: '物流配送' }, // 物流配送
          { key: 'stores', name: '门店自提' }, // 门店自提
        ],
        current: 0 // 0 - 物流配送； 1 - 门店自提
      },
      ztStore: {
        initState: true, // 初始进入状态
        orderId: '', // 订单id
      },
      updateTimeStamp: 0, // 添加抬头时间戳，用于判断增加抬头后刷新发票选择列表
      listData: {}, // 存储配送时间接口返回的数据 用于子页面的渲染
      initTime: true, //打个标记 此变量代表是初始化 需要渲染的配送时间
      initTimeChangTab: true, // 此变量代表 切换了自提 活物流配送 时 时间还得赋值显示默认时间
      changeAdress: false,
      isClick: 1001, //默认选中在线支付
    }
  },
  computed: {
    curOrderDetailData() {
      return this.orderDetailData
    },
    // 是物流配送
    isLogistics() {
      return this.topTabs.current == 0
    },
    // 来自触屏跳转
    isFromTouchScreen() {
      return this.ztStore.orderId
    },
    polylinePoints() {
      const { curLat, curLng } = this.settleParams ?? {}
      const { latitude, longitude } = this.ztInfo?.location ?? {}
      const points = [
        { latitude: curLat, longitude: curLng },
        { latitude, longitude }
      ]
      return points
    },
    // 预览地图定位
    previewLocate() {
      const { curLat, curLng } = this.settleParams ?? {}
      if (curLat && curLng) {
        const location = {
          latitude: curLat ?? null,
          longitude: curLng ?? null
        }
        return location
      }
      return this.ztInfo?.location ?? {}
    },
    // 地图显隐
    isShowMap() {
      const { latitude, longitude } = this.ztInfo?.location ?? {}
      const hasLocateInfo = latitude && longitude
      return !this.isLogistics && hasLocateInfo
    },
    // 预览小图makers
    markersPoints() {
      const markers = [{
        ...this.ztInfo.location,
        iconPath: '/static/image/icon_store@2x.png',
        width: 60,
        height: 60
      }]
      return markers
    }
  },
  watch: {
    /*发票抬头时间戳变化，更新数据*/
    updateTimeStamp: {
      handler(newVal) {
        this.$refs.invoice.queryInvoiceFn()
      },
      deep: true
    },
    /*监听收货地址变化，重新获取结算单*/
    shippingAddressModel: {
      handler(newVal, oldVal) {
        this.disableDeliverWayCell(newVal)
        if (
          !oldVal || (Object.keys(oldVal).length > 0 &&
          newVal &&
          newVal.ship_add_id != oldVal.ship_add_id)
        ) {
          this.settleParams.shippingAddressModel = this.shippingAddressModel
          this.settleParams.selfAddressModel = null; //切换地址时，清空选择的自提地址
          this.orderInfo.changeDate = ''
          this.orderInfo.changeTime = ''
          this.changeAdress = true
          // console.log('shippingAddressModel');
          this.settleOrderFn('', true)
        }
      },
      immediate: false,
    },
  },
  onLoad(options) {
    // console.log('onLoad :>> ', options);
    let skuList = []
    if (options && Object.keys(options).length > 0 && options.skuList) {
      skuList = JSON.parse(decodeURIComponent(options.skuList)) //sku列表
    }
    let scanRunState = true
    if (options?.q) { // 智慧屏微信扫码会携带q，进行对应的逻辑处理(微信扫码)
      scanRunState = this.executeWeinXinScanResult(options.q)
    }
    if (this.vuex_alipay_qrcode) { // 智慧屏微信扫码会携带q，进行对应的逻辑处理(支付宝扫码)
      scanRunState = this.executeWeinXinScanResult(this.vuex_alipay_qrcode)
    }
    if (options?.orderId) { // 智慧屏小程序扫码会携带orderId，进行对应的逻辑处理
      scanRunState = this.executeMiniScanResult(options.orderId)
    }
    if (!scanRunState) return
    // console.log('skuList :>> ', skuList);
    this.initPageFn(skuList)
  },
  methods: {
    /*订单页面配送方式默认回显*/
    initDataTime(val) {
      this.initTime = false
      const nbsp = ' '
      this.$set(this.orderInfo, 'deliverWay', val.deliverWay)
      this.$set(this.orderInfo, 'changeDate', val.changeDate)
      this.$set(this.orderInfo, 'changeTime', val.changeTime)
      this.orderInfo.deliverWayText = this.setDeliverWayFn(val.deliverWay) + nbsp + val.changeDate + nbsp + val.changeTime
      console.log('这是点击弹框确定按钮回传出来的选中的时间段', val.deliverWay, val.changeDate, val.changeTime);
    },
    /* 初始化订单页面 需要回显配送方式及时间段*/
    /* 调取配送时间*/
    /**
     * orderType : 1. 快递、快运、专车: 10-配送订单 2. 鑫方盛物流-有专线编码：20-专线订单（此时时效使用专线时效specialLinePrescription）3. 鑫方盛物流-无专线编码：10-配送订单
     */
    getOrderTypeFn(curOrderInfo) {
      let getDeliveryTimeData = {
        'orderType': '', //订单类型
        'deliverEffectTime': '', //配送时效
        'dev': '', //选中的配送方式
        'truckShift': '', //专线订单-配送周期（班次）
        'lastDeliveryDate': '', //专线订单-上次送货日
      }
      const dev = curOrderInfo.deliverWay
      let deliverWayListObj = {} //页面上的配送方式基础信息包括时效 专线编码
      if (curOrderInfo.deliverWayList && curOrderInfo.deliverWayList.length > 0) {
        const curList = curOrderInfo.deliverWayList;
        for (var i = 0; i < curList.length; i++) {
          deliverWayListObj[curList[i].code] = curList[i];
        }
      } else {
        deliverWayListObj = {};
      }

      if (deliverWayListObj[dev].specialLineCode && dev == 'private') {
        getDeliveryTimeData = {
          'orderType': 20,
          'deliverEffectTime': deliverWayListObj[dev].specialLinePrescription,
          'dev': dev,
          'truckShift': deliverWayListObj[dev].truckShift,
          'lastDeliveryDate': deliverWayListObj[dev].lastDeliveryDate,
        }
      }
      if ((!deliverWayListObj[dev].specialLineCode && dev == 'private') || dev == 'kd' || dev == 'ky' || dev == 'car' || dev == 'kyMy') {
        getDeliveryTimeData = {
          'orderType': 10,
          'deliverEffectTime': deliverWayListObj[dev].prescription,
          'dev': dev,
          'truckShift': deliverWayListObj[dev].truckShift,
          'lastDeliveryDate': deliverWayListObj[dev].lastDeliveryDate,
        }
      }
      return getDeliveryTimeData
    },
    deliverContentInit(curOrderInfo) {
      this.listData = {}
      const getOrderTypeObj = this.getOrderTypeFn(curOrderInfo);
      const params = {
        'orderType': getOrderTypeObj.orderType, //订单类型。10：配送订单；20：专线订单；
        'deliverWay': getOrderTypeObj.dev, // 选中的物流方式。private：自有物流; kd：快递; ky：快运; car：专车包车;
        'deliverEffectTime': getOrderTypeObj.deliverEffectTime, // 配送时效(专线订单或者配送订单的配送时效)
        'maxArrivalCycle': curOrderInfo.maxArrivalCycle, // 最大到货周期
        'addressIsLimit': curOrderInfo.shippingAddressModel.limitLine, // 是否限行。10：限行；20：不限行
        'maxLength': curOrderInfo.maxLength, //商品-最大长度（厘米）
        'goodTotalWeight': curOrderInfo.goodTotalWeight, //商品-总重量（千克）
        'goodTotalVolume': curOrderInfo.goodTotalVolume, //商品-总体积（立方厘米）
        'truckShift': getOrderTypeObj.truckShift, //专线订单-配送周期（班次）
        'lastDeliveryDate': getOrderTypeObj.lastDeliveryDate, //专线订单-上次送货日
        'ruleVersion': 20230530
      }
      const nbsp = ' '
      getPostTime(params).then((res) => {
        if (res.code == 0) {
          this.listData = res.data
          this.orderInfo.changeDate = this.listData.deliveryDate //初始化默认的数据
          this.orderInfo.changeTime = this.listData.deliveryTime //初始化默认的数据
          if (this.initTime && this.initTimeChangTab) { //初始化配送方式默认取值 从这里赋值
            console.log('初始化进来', this.listData.deliveryDate + this.listData.deliveryTime)
            this.orderInfo.deliverWayText = this.setDeliverWayFn(this.orderInfo.deliverWay) + nbsp + this.listData.deliveryDate + nbsp + this.listData.deliveryTime
          }
          if (this.changeAdress) {
            console.log('切换了地址', this.listData.deliveryDate + this.listData.deliveryTime)
            this.orderInfo.deliverWayText = this.setDeliverWayFn(this.orderInfo.deliverWay) + nbsp + this.listData.deliveryDate + nbsp + this.listData.deliveryTime
          }
        } else {
          this.$u.toast('获取配送时间失败')
        }
      })
    },
    // 初始化自提时间
    initSelfPickupTime() {
      const { orderData, selfAddressModelObj } = this
      const hasOrderData = orderData && Object.keys(orderData).length > 0
      const takeTimeObj = {
        '上午': '12:00:00',
        '下午': '18:00:00',
      }
      const hasSelfAddressModelObj = selfAddressModelObj && Object.keys(selfAddressModelObj).length > 0
      if (hasOrderData && hasSelfAddressModelObj) {
        const { maxArrivalCycle = '0', storeSufficient = 0, selfAddressModel = {}} = orderData
        const { transferCycle = 0, selfTakeHour = 0, selfTakeType } = selfAddressModel || {}
        const params = {
          selfPickupType: selfTakeType, // 自提类型。10：门店自提；20：物流自提；
          maxArrivalCycle: maxArrivalCycle, // 最大到货周期
          transferCycle: transferCycle, // 调货周期
          storeSufficient: storeSufficient, // 门店库存是否充足。0：充足；1：不充足
          selfRequestedStr: selfTakeHour, // 自提要求-自提时间点。传数字格式，例如：8、12、23
          ruleVersion: undefined,
        }
        getSelfPickupTime(params).then((resp) => {
          const { code, data } = resp || {}
          if (code === '0' && data) {
            this.selfPickupTimeInfo = data
            const { selfPickupTime, selfPickupDate, weekStr, amPm, selfRequested, modifyFlag, selectDate } = data || {}
            const [year, month, day] = selfPickupDate.split('-')
            const week = weekStr.replace('【', '').replace('】', '')
            const label = `${month}月${day}日 ${week} ${amPm || ''} ${selfRequested ? selfRequested + '点后' : ''}`
            this.selfAddressModelObj.maxArrivalCycle = maxArrivalCycle
            this.selfAddressModelObj.selfTakeTimeObj = {
              selfPickupTime,
              selfTakeTime: takeTimeObj[amPm],
              year,
              month,
              day,
              week,
              amPm,
              dateStr: `${year}${month}${day}`,
              label: label.trim()
            }
            this.updateZtTime()
            if (modifyFlag && modifyFlag === 20 && selectDate && selectDate.length) {
              this.changeUseStateZtTime(false) // 启用可选择自提时间
            } else {
              this.changeUseStateZtTime(true) // 禁用可选择自提时间
            }
          } else {
            this.changeUseStateZtTime(true) // 禁用可选择自提时间
          }
        })
      } else {
        this.changeUseStateZtTime(true) // 禁用可选择自提时间
      }
    },

    /*重试*/
    testAgainFn(method) {
      this[method]()
    },
    /*返回购物车*/
    backPurchaseFn() {
      uni.redirectTo({
        url: `/purchaseOrder/index`
      })
    },
    /*收货地址编辑*/
    editAddressFn() {
      uni.navigateTo({
        url: `/address/addressList?type=order&id=${(!this.shippingAddressModel || Object.keys(this.shippingAddressModel).length == 0) ? '' : this.shippingAddressModel.ship_add_id}`
      })
    },
    freightFn(e) {
      this.freightFlag = false
      this.priceInfo.freightType = e
      this.priceInfo.freightTypeText = this.setFreightTypeFn(e)
      this.freightAllocationFn()
    },
    closeFication(e) {
      this.orderInfo.needQualificationText = this.setNeedQualificationFn(e.needQualificationChoosen)
    },
    showFreFn() {
      this.freightFlag = true
    },
    showCouponFn() {
      this.couponFlag = true
    },
    /*选中配送方式执行方法*/
    deliverWayChangeFn(val, num) {
      if (num == 1) { //num ==1 是更新商品价格时用到的数据
        this.orderInfo.deliverWay = val.deliverWay
        this.settleParams.deliverWay = val.deliverWay || this.orderInfo.deliverWay
      } else {
        this.orderInfo.deliverWay = val
        this.settleParams.deliverWay = val || this.orderInfo.deliverWay
      }

      this.settleParams.selfAddressModel = null
      this.orderInfo.changeDate = ''//点击了鑫方盛快递物流按钮 时间置空否则显示undefind
      this.orderInfo.changeTime = '' //点击了鑫方盛快递物流按钮 时间置空否则显示undefind
      console.log('这是点击了鑫方盛快递物流按钮', val, this.orderInfo.deliverWay)
      this.ztHideSendTypeFn()
      if (val) { // 选择配送方式触发，不校验库存
        this.isVerifyInventory = false
      } else {
        this.isVerifyInventory = true
      }
      this.settleOrderFn(10, true)
    },
    /*选中自提地址执行方法*/
    selfAddressSelectFn(userChangeDeliver) {
      this.settleParams.deliverWay = 'zt'
      this.settleParams.selfAddressModel = this.selfAddressModelObj?.selfAddressModel
      this.updateAddressPersonList()
      this.isVerifyInventory = true
      this.ztHideSendTypeFn()
      this.settleOrderFn(userChangeDeliver==10?10:undefined, true)
    },
    /*发货方式根据配送方式判断展示*/
    ztHideSendTypeFn() {
      const orderFilterCells = ['deliverWay', 'sendType']
      this.orderCellColumn.forEach((item, index) => {
        const isFilter = orderFilterCells.includes(item.customParams.popPage)
        if (this.settleParams.deliverWay == 'zt' && isFilter) {
          this.orderCellColumn[index].hideCell = true
          this.priceCellColumn[1].hideCell = true
          this.priceCellColumn[2].hideCell = true
        }
        if (this.settleParams.deliverWay != 'zt' && isFilter) {
          this.orderCellColumn[index].hideCell = false
          this.priceCellColumn[1].hideCell = false
          this.priceCellColumn[2].hideCell = false
        }
      })
    },
    /*选中优惠券执行方法*/
    couponChangeFn() {
      const couponObj = this.priceInfo.couponChoosen
      if (Object.keys(couponObj).length > 0) {
        this.settleParams.couponCodeChoosen = couponObj.couponCode
        this.settleParams.couponType = couponObj.couponType
      } else {
        this.settleParams.couponCodeChoosen = 0;
        this.settleParams.couponType = 0;
      }
      this.settleOrderFn(10, true)
    },
    initPageFn(skuList) {
      const {
        warehouseCode,
        cityCode,
      } = this.vuex_cityInfo
      this.settleParams.cityId = cityCode
      this.settleParams.warehouseId = warehouseCode
      // #ifdef H5
      if (skuList && skuList.length > 0) {
        this.shoppingCartList = skuList
        this.setSettleParamsFn()
      } else if (this.ztStore.orderId) {
        // 如果有orderId，就加载切换tab方式，定位到门店自提
        this.selfAddressSelectFn()
      } else {
        this.getShoppingCartListFn()
      }
      // #endif

      // #ifdef MP-ALIPAY || MP-WEIXIN
      this.getLocationFn().then(() => {
        if (skuList && skuList.length > 0) {
          this.shoppingCartList = skuList
          this.setSettleParamsFn()
        } else if (this.ztStore.orderId) {
          // 如果有orderId，就加载切换tab方式，定位到门店自提
          this.selfAddressSelectFn()
        } else {
          this.getShoppingCartListFn()
        }
      }).catch(() => {
        this.$u.toast('定位失败')
        if (skuList && skuList.length > 0) {
          this.shoppingCartList = skuList
          this.setSettleParamsFn()
        } else if (this.ztStore.orderId) {
          // 如果有orderId，就加载切换tab方式，定位到门店自提
          this.selfAddressSelectFn()
        } else {
          this.getShoppingCartListFn()
        }
      })
      // #endif
    },
    /*未登录跳转登录*/
    returnLoginFn(extraParams = {}) {
      const callbackUrl = `/ycPayments/confirmOrders/index`
      const urlParams = JSON.stringify({ pageSource: 'local', ...extraParams })
      // #ifdef MP-ALIPAY || MP-WEIXIN
      uni.navigateTo({
        url: `/login/login/codeLogin?type=confirm&callbackUrl=${callbackUrl}&urlParams=${urlParams}`
      })
      // #endif
      //#ifdef H5
      uni.navigateTo({
        url: `../../login/login/mCodeLogin?type=order&callbackUrl=${callbackUrl}&urlParams=${urlParams}`
      })
      // #endif
    },
    /*获取购物列表*/
    getShoppingCartListFn() {
      this.shoppingCartList = []
      let paramWarehouseCode = ''
      let paramProvinceCode = ''
      let paramCityCode = ''
      if (this.curDeliverWay == 'zt' && this.selfAddressModelObj && Object.keys(this.shippingAddressModel).length > 0) {
        const {
          warehouse_code,
          province_code,
          city_code,
        } = this.selfAddressModelObj?.selfAddressModel
        paramWarehouseCode = warehouse_code
        paramProvinceCode = province_code
        paramCityCode = city_code
      } else if (this.curDeliverWay != 'zt' && this.shippingAddressModel && Object.keys(this.shippingAddressModel).length > 0) { //有默认选中地址时取地址中的code，没有时取站点code，保证价格统一
        const {
          warehouse_code,
          province_code,
          city_code,
        } = this.shippingAddressModel
        paramWarehouseCode = warehouse_code
        paramProvinceCode = province_code
        paramCityCode = city_code
      } else {
        const {
          warehouseCode,
          provinceCode,
          cityCode,
        } = this.vuex_cityInfo
        paramWarehouseCode = warehouseCode
        paramProvinceCode = provinceCode
        paramCityCode = cityCode
      }
      const {
        memberId,
        accountType,
        loginAccount,
        mainCustomerId
      } = this.vuex_memberInfo
      if (this.vuex_crmCustomerInfos && this.vuex_crmCustomerInfos.length > 0) {
        var {
          customerId
        } = this.vuex_crmCustomerInfos[0]
      }
      const params = {
        memberId: memberId,
        cityId: paramCityCode,
        customerId: customerId || '',
        token: this.vuex_token,
        warehouseId: paramWarehouseCode,
        platformType: accountType == 10 ? 1 : 2,
        accountType: accountType,
        loginAccount: loginAccount,
        isMiniOrderStatus: 20, //是否使用最小起订量  10:是 20：否
        curSiteCode: paramProvinceCode,
        mainCustomerId: mainCustomerId || ''
      }
      getShoppingCartList(params).then((res) => {
        if (Number(res.code) != 0) {
          this.$u.toast(res.msg)
          return
        }
        const promotionProducts = res.promotionProducts
        if (promotionProducts && promotionProducts.length > 0) {
          promotionProducts.forEach((item) => {
            item.shoppingCartList.forEach((shopCarListItem) => {
              shopCarListItem.forEach((skuItem) => {
                if (skuItem.selectedStatus == 10) {
                  const skuInfo = {
                    buyyerCount: skuItem.productCount,
                    cartId: skuItem.id,
                    salePrice: skuItem.salePrice,
                    skuCode: skuItem.sku_code,
                    itemId: skuItem.itemId,
                    opsRequestMisc: skuItem.opsRequestMisc,
                    requestId: skuItem.requestId,
                    spuCode: skuItem.spuCode,
                    inquiryId: skuItem.inquiryId,
                  }
                  if (skuItem.promotionProductTag == 10) {
                    skuInfo.joinPromotionTag = skuItem.activityParticipate
                    skuInfo.activityId = skuItem.activityId
                  } else {
                    skuInfo.joinPromotionTag = 10
                    skuInfo.activityId = ''
                  }

                  if (skuItem.isTemporaryPurchase == 1) {
                    skuInfo.tempPurchase = 10
                  }
                  this.shoppingCartList.push(skuInfo)
                }
              })
            })
          })
        }
        // console.log('this.shoppingCartList :>> ', this.shoppingCartList);
        this.setSettleParamsFn()
      })
    },
    /*组装获取结算订单参数*/
    setSettleParamsFn() {
      if (this.shoppingCartList.length <= 0) { // 当选中的商品为空时，返回购物车
        setPageParamsFn(this, 'EMPTY', '您所购买的商品被抢光了', true, 'backPurchaseFn', '返回购物车')
        return
      }
      this.settleParams.skuList = this.shoppingCartList
      this.settleParams.userChangeDeliver = '' // 是否用户主动切换配送方式
      // console.log('setSettleParamsFn');
      this.settleOrderFn('', true)
    },
    /*获取结算订单*/
    settleOrderFn(userChangeDeliver, isSetDeliverWay) {
      this.modalOptions.custom.continueBuyingHandleType = ''
      this.settleParams.userChangeDeliver = userChangeDeliver || ''
      if (this.shippingAddressModel && Object.keys(this.shippingAddressModel).length > 0) {
        this.settleParams.cityId = this.shippingAddressModel.city_code
        this.settleParams.warehouseId = this.shippingAddressModel.warehouse_code
      }
      const { orderId } = this.ztStore
      const settleParams = { ...this.settleParams }
      if (this.isLogistics) delete settleParams.selfAddressModel
      if (userChangeDeliver == 10 && this.settleParams.deliverWay == 'zt'){
         delete settleParams.selfAddressModel
         this.ztInfo = {}
      }
      const params = orderId ? { ...settleParams, orderId, version_code: 1 } : settleParams
      const orderRequest = orderId ? preSettleOrder : settleOrder
      orderRequest(params).then((res) => {
        // console.log('orderRequest :>> ', res);
        this.orderData = res
        const {
          payModelChoosen,
          payModelList,
          deliverWay, // 默认选中物流方式: private-自有物流; kd-快递; ky-快运; car-专车包车; zt-上门自提 及运费
          deliverWayList, // 配送方式列表： private-自有物流; kd-快递; ky-快运-送货上门; kyMy-快运-站点自提; car-专车包车; zt-上门自提
          deliverWayItem = this.getDeliverWayItemFn(deliverWay, deliverWayList),
          couponChoosen, // 默认选中的优惠券
          couponSpuSkuBoList, // 优惠券列表
          needQualification, // 是否展示资质选项 10-展示；20-不展示
          needQualificationChoosen = '20', //是否要资质：10-需要；20-不需要
          needRedChapter, //是否带红章：10-是；20-否
          qualificationNum, // 资质份数
          goodTotalMoney, // 商品总额
          freightType, // 运费类型：10-单开；20-分摊；null-不限
          reduceTotalMoney, // 立减金额
          payTotalMoney, // 支付金额
          selfAddressModel, // 选中的自提地址
          selfTakeAddressList, // 自提地址列表
          shippingAddressModel, // 选中的收货地址
          shoppingAddList, // 收货地址列表
          logisticsCenterAddressList, //物流中心列表
          maxArrivalCycle,
          maxLength,
          goodTotalVolume,
          goodTotalWeight,
          // storeSufficient, // 门店库存是否充足：0-充足；1-不充足
          // serverTime, // 服务器时间
          products,
          abnormalProducts,
        } = res
        if (products.length > 0) { //当选择的商品包含临采商品时，订单确认页不展示门店自提
          const productTypeT = products.some(item => {
            return item.productType == 20 // 当有数组有一项满足条件时结束并返回true //商品类型：10-正常商品；20-临采商品；30-供货商商品
          })
          if (productTypeT) {
            this.topTabs.list.splice(1, 1)
          }
        }
        const {
          invoice,
        } = this.submitInvoiceInfo
        if (needQualification == 10) {
          const quaCell = {
            label: '资质文件',
            labelStyle: 'font-size: 24rpx;color: #666;',
            fields: ['needQualificationText'],
            customParams: {
              popPage: 'needQualification'
            },
            showRightIcon: true,
            methodName: 'showPopFn'
          }
          this.orderCellColumn[this.orderCellColumn.length - 2] = quaCell
        } else {
          const quaIndex = this.orderCellColumn.findIndex(item => item.fields[0] == 'needQualificationText')
          if (quaIndex != -1) {
            this.orderCellColumn.splice(quaIndex, 1)
          }
        }
        const selfInvoiceStr = `个人${invoice?.invoiceTitle ? '-' + invoice.invoiceTitle : ''}`
        const companyInvoiceStr = `单位${invoice?.invoiceTitle ? '-' + invoice.invoiceTitle : ''}`
        const invoiceStrMaps = {
          0: `增值税发票${invoice?.invoiceTitle ? '-' + invoice.invoiceTitle : ''}`,
          1: invoice?.taxId ? companyInvoiceStr : selfInvoiceStr
        }
        const invoiceFlagText = invoiceStrMaps[Number(this.invoiceType)] ?? '不开发票'
        let payName = ''
        if (payModelChoosen.payType == '1301') {
          payName = '银行转账'
        } else {
          payName = payModelChoosen.payName
        }
        const tempDeliverWay = deliverWay
        this.orderInfo.deliverWay = deliverWay
        if (this.isLogistics) {
          this.tempDeliverWay = tempDeliverWay
        }
        this.curDeliverWay = deliverWay || deliverWayList[0].code
        deliverWayList.map((item) => {
          item.deliverWayText = this.setDeliverWayFn(item.code)
          return item
        })
        if (deliverWayList.length == 1 && deliverWay == '' && deliverWayList[0].code == 'zt') { //默认如果是自提 时间置空否则显示undefind
          this.orderInfo.changeDate = ''
          this.orderInfo.changeTime = ''
        }
        const nbsp = ' '
        this.orderInfo = {
          payName: payName,
          payType: payModelChoosen.payType,
          payModelChoosen,
          payModelList,
          deliverWay: tempDeliverWay,
          deliverWayText: this.setDeliverWayFn(tempDeliverWay) + nbsp + this.orderInfo.changeDate + nbsp + this.orderInfo.changeTime, //页面回显配送时间拼接
          deliverWayList,
          sendType: 0,
          sendTypeText: '货齐再发',
          sendTypeList: [
            {
              sendType: 0,
              sendTypeText: '货齐再发',
            },
            {
              sendType: 1,
              sendTypeText: '有货先发',
            }
          ],
          needQualificationChoosen, //是否要资质：10-需要；20-不需要
          needRedChapter, //是否带红章：10-是；20-否
          needQualificationText: this.setNeedQualificationFn(needQualificationChoosen),
          qualificationNum, // 资质分数
          orderRemark: '',
          invoiceFlagText: invoiceFlagText,
          maxLength,
          maxArrivalCycle,
          goodTotalVolume,
          goodTotalWeight,
          shippingAddressModel
        }
        if (deliverWay != 'zt' && deliverWay != '') {
          this.deliverContentInit(this.orderInfo)
        }

        if (this.isLogistics) { // 只缓存物流配送状态的配送方式
          this.tempDeliveryWay = deliverWay
        }
        this.priceInfo = {
          goodTotalMoney,
          freight: deliverWayItem.freight || 0,
          originFreight: deliverWayItem.freight,
          originGoodTotalMoney: goodTotalMoney,
          freightType: freightType || 10,
          freightTypeText: this.setFreightTypeFn(freightType || 10),
          reduceTotalMoney,
          couponRealValue: couponChoosen ? Number(couponChoosen.couponRealValue).toFixed(2) : '0.00',
          couponChoosen,
          couponSpuSkuBoList,
          payTotalMoney,
        }
        this.priceCellColumn[this.priceCellColumn.length - 1].hideCell = couponSpuSkuBoList.length == 0
        this.shippingAddressModel = shippingAddressModel
        this.shoppingAddList = shoppingAddList
          if (deliverWay == 'zt') {
            this.selfAddressModelObj = this.selfAddressModelObj || {
              mobile: (shippingAddressModel && Object.keys(shippingAddressModel).length > 0) ? (shippingAddressModel.addressPersonList[0].mobile || '') : '',
              receiverName: (shippingAddressModel && Object.keys(shippingAddressModel).length > 0) ? (shippingAddressModel.addressPersonList[0].receiverName || '') : '',
              selfTakeTimeObj: {},
              selfAddressModel,
              shipAddId: selfAddressModel ? selfAddressModel.ship_add_id || 0 : selfAddressModel,
              selfTakeAddressList,
              logisticsCenterAddressList
            }
            const info = this.getZtStoreInfo(this.selfAddressModelObj)
            this.ztInfo.mobile = info.mobile
            this.ztInfo.receiverName = info.receiverName
            if(userChangeDeliver !== 10) {
              this.ztInfo.addAlias = info.addAlias
            this.ztInfo.location = info.location
              this.changeUseStateZtTime(false) // 启用可选择自提时间
            } else {
              this.changeUseStateZtTime(true) // 禁用可选择自提时间
            }
        }
        // 初始化时获取自提时间
        if (!userChangeDeliver && deliverWay == 'zt') {
          this.initSelfPickupTime()
        }
        if (!userChangeDeliver && this.isVerifyInventory && res.code == 61) {
          if (abnormalProducts.length > 0) {
            if (deliverWay == 'zt' && this.ztInfo.addAlias) {
              this.abnormalModalFn(products, abnormalProducts, res.code)
            } else {
              this.abnormalModalFn(products, abnormalProducts, res.code)
            }
          }
        }
      })
    },
    /*无货异常弹框提示*/
    abnormalModalFn(products, abnormalProducts, errorCode) {
      // console.log('products :>> ', products);
      const abnormalObj = {
        changeSku: [], // 价格变化
        changeSkuList: [],
        quehuoSku: [], // 缺货
        minNumList: [], //最小起订量不足
        minNumSkuList: [], //最小起订量不足 skuList
        cartIdList: [], // 无货carIdlist
        skuCodeList: [], // 无货skuCode
        skuList: [], // 无货skuCode
        tomoSkuList: [], // 第二天自提skuCode
      }
      abnormalProducts.forEach((item) => {
        if (item.code == 79) {
          abnormalObj.minNumList.push(item.skuCode)
          abnormalObj.minNumSkuList.push(item)
        }
        if (item.code == 70 || item.code == 75) {
          abnormalObj.changeSku.push(item.skuCode)
          abnormalObj.changeSkuList.push(item)
        } else {
          if (item.code != 78 && item.code != 79) {
            abnormalObj.quehuoSku.push(item.skuCode)
          }
          if (item.code == 78) {
            abnormalObj.tomoSkuList.push(item.skuCode)
          }
          abnormalObj.cartIdList.push(Number(item.cartId))
          abnormalObj.skuCodeList.push(item.skuCode)
          abnormalObj.skuList.push(item)
        }
      })
      this.abnormalObj = abnormalObj
      const {
        minNumSkuList,
        changeSkuList,
        skuList,
        tomoSkuList,
      } = abnormalObj
      this.modalOptions.modalShow = true
      if (this.orderInfo.deliverWay == 'zt' && skuList.length > 0 && products.length == skuList.length) { //如果选择自提，且有异常商品不能当天自提时，则弹框提示 全部无货
        this.modalOptions.custom.showConfirmButton = true
        if (tomoSkuList.length === 0 || tomoSkuList.length != skuList.length) {
          this.modalOptions.custom.confirmText = '修改自提点'
          this.modalOptions.custom.confirmOperation = 'selectStore' // 修改自提点
          this.modalOptions.custom.cancelText = '修改数量'
          this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
          this.modalOptions.custom.title = '您购买的全部商品无货，请重新选择自提点，或者返回购物车修改购买数量。'
        } else {
          this.modalOptions.custom.confirmText = '确认购买'
          this.modalOptions.custom.confirmOperation = 'continueBuying' // 继续购买
          this.modalOptions.custom.cancelText = '返回'
          this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
          this.modalOptions.custom.title = '您购买的全部商品无法当天自提，如果继续购买将为您更新自提时间，是否继续购买？'
        }
        this.modalOptions.modalList = []
        return;
      }
      if (this.orderInfo.deliverWay == 'zt' && skuList.length > 0 && products.length > skuList.length) { //如果选择自提，且有异常商品不能当天自提时，则弹框提示 部分无货
        if (tomoSkuList.length !== 0 && tomoSkuList.length === skuList.length) {
          this.modalOptions.custom.showConfirmButton = true
          this.modalOptions.custom.confirmText = '确认购买'
          this.modalOptions.custom.confirmOperation = 'continueBuying' // 继续购买
          this.modalOptions.custom.cancelText = '返回'
          this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
          this.modalOptions.custom.title = '您购买的部分商品无法当天自提，如果继续购买将为您更新自提时间，是否继续购买？'
          this.modalOptions.modalList = skuList
        } else {
          this.modalOptions.custom.confirmText = '仅购买有货商品'
          this.modalOptions.custom.showConfirmButton = true
          this.modalOptions.custom.confirmOperation = 'changCartProduct' // 是否购物车无货商品取消勾选
          this.modalOptions.custom.cancelText = '返回'
          this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
          this.modalOptions.custom.title = `抱歉，您购买的以下${skuList.length}个商品无货！`
          this.modalOptions.modalList = skuList
        }
        return
      }
      if (this.orderInfo.deliverWay != 'zt' && skuList.length > 0 && products.length == skuList.length) { //全部无货
        this.modalOptions.custom.confirmText = '更换地址'
        this.modalOptions.custom.showConfirmButton = true
        this.modalOptions.custom.confirmOperation = 'updateAddress' // 更换地址
        this.modalOptions.custom.cancelText = '返回'
        this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
        this.modalOptions.custom.title = '抱歉，您购买的本单商品全部无货！'
        this.modalOptions.modalList = []
        return;
      }
      if (this.orderInfo.deliverWay != 'zt' && skuList.length > 0 && products.length > skuList.length) { //部分无货
        this.modalOptions.custom.confirmText = '仅购买有货商品'
        this.modalOptions.custom.showConfirmButton = true
        this.modalOptions.custom.confirmOperation = 'changCartProduct' // 是否购物车无货商品取消勾选
        this.modalOptions.custom.cancelText = '返回'
        this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
        this.modalOptions.custom.title = `抱歉，您购买的以下${skuList.length}个商品无货！`
        this.modalOptions.modalList = skuList
        return
      }
      if (minNumSkuList.length > 0) { // 起订量不足
        this.modalOptions.custom.confirmText = '更换地址'
        this.modalOptions.custom.showConfirmButton = true
        this.modalOptions.custom.confirmOperation = 'updateAddress' // 更换地址
        this.modalOptions.custom.cancelText = '返回'
        this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
        this.modalOptions.custom.title = `抱歉，您购买的以下${minNumSkuList.length}个商品因采购数量不少于起订量要求．请增加采购数量！`
        this.modalOptions.modalList = changeSkuList
        return
      }
      if (changeSkuList.length > 0) { // 价格变更
        this.modalOptions.custom.confirmText = '更新价格'
        this.modalOptions.custom.showConfirmButton = true
        this.modalOptions.custom.confirmOperation = 'updatePrice'
        this.modalOptions.custom.cancelText = '返回'
        this.modalOptions.custom.cancelOperation = 'backPurchaseOrder' // 是否返回购物车
        this.modalOptions.custom.title = `抱歉，您购买的以下${changeSkuList.length}个商品价格变更！`
        this.modalOptions.modalList = changeSkuList
        return
      }
    },
    /*取消购物车选中*/
    changCartProduct: function() {
      const params = { updateCartList: [] }
      this.abnormalObj.cartIdList.forEach((item) => {
        params.updateCartList.push({
          cartId: item,
          selectedStatus: 20
        })
      })
      joinPromotion(params).then((res) => {
        if (res.code == 0) {
          this.getShoppingCartListFn(); //修改状态成功后重新刷新列表
        } else {
          this.$u.toast(res.msg)
        }
      })
    },
    /*配送方式转换*/
    setDeliverWayFn(deliverWay) {
      let deliverWayText = ''
      switch (deliverWay) {
        case 'private':
          deliverWayText = '鑫方盛物流'
          break
        case 'kd':
          deliverWayText = '快递'
          break
        case 'ky':
          deliverWayText = '快运（送货上门）'
          break
        case 'kyMy':
          deliverWayText = '快运（站点自提）'
          break
        case 'car':
          deliverWayText = '专车包车'
          break
        case 'zt':
          deliverWayText = '门店自提'
          break
        default:
          deliverWayText = ''
          break
      }
      return deliverWayText
    },
    /*获取选中的配送方式*/
    getDeliverWayItemFn(deliverWay, deliverWayList) {
      let deliverWayItem = {}
      for (let i = 0; i < deliverWayList.length; i++) {
        if (deliverWayList[i].code == deliverWay) {
          deliverWayItem = deliverWayList[i]
          break
        }
      }
      return deliverWayItem
    },
    /*是否需要资质转换方法*/
    setNeedQualificationFn(needQualificationChoosen) {
      let needQualificationVal = ''
      switch (Number(needQualificationChoosen)) {
        case 10:
          needQualificationVal = '需要'
          break
        case 20:
          needQualificationVal = '不需要'
          break
        default:
          needQualificationVal = '不需要'
          break
      }
      return needQualificationVal
    },
    /*是否需要资质转换方法*/
    setFreightTypeFn(freightType) {
      let freightTypeVal = ''
      switch (Number(freightType)) {
        case 10:
          freightTypeVal = '运费单开'
          break
        case 20:
          freightTypeVal = '运费分摊'
          break
        default:
          freightTypeVal = ''
          break
      }
      return freightTypeVal
    },
    /*运费分摊算法*/
    freightAllocationFn() {
      const {
        freightType,
        freight,
        goodTotalMoney,
        originGoodTotalMoney,
        originFreight,
      } = this.priceInfo
      const {
        products
      } = this.orderData
      let freightSum = 0
      if (freightType == 20) { // 分摊
        this.priceInfo.freight = 0
        this.priceInfo.goodTotalMoney = (Number(originFreight) + Number(originGoodTotalMoney)).toFixed(2)
        products.map((item, index) => {
          if (index == products.length - 1) {
            item.freightAllocationVal = (Number(freight) - Number(freightSum)).toFixed(2)
          } else {
            const itemFreight = (Number(freight) * (Number(item.salePrice) / Number(goodTotalMoney))).toFixed(2)
            item.freightAllocationVal = itemFreight
            freightSum = (Number(freightSum) + Number(itemFreight)).toFixed(2)
          }
          return item
        })
      } else { //单开
        this.priceInfo.freight = originFreight
        this.priceInfo.goodTotalMoney = originGoodTotalMoney.toFixed(2)
        products.map((item) => {
          item.freightAllocationVal = 0
          return item
        })
      }
    },
    /*拼装确认参数*/
    makeConfirmOrderParamsFn() {
      this.updateAddressPersonList()
      //默认支付方式在线支付
      this.orderInfo.payModelChoosen = this.orderInfo.payModelChoosen ? this.orderInfo.payModelChoosen : {
        id: '',
        payName: '在线支付',
        payType: '1001'
      }
      const {
        payModelChoosen,
        sendType,
        orderRemark,
        needQualificationChoosen,
        needRedChapter,
        qualificationNum,
        deliverWay,
        deliverWayList
      } = this.orderInfo
      const {
        goodTotalMoney,
        originFreight,
        freightType,
        couponChoosen,
        payTotalMoney,
      } = this.priceInfo
      //各种金额
      let finalTotalAmount = 0
      if (deliverWayList.length > 0 && deliverWay) {
        finalTotalAmount = Number(goodTotalMoney) + Number(originFreight); //订单总金额
      } else {
        finalTotalAmount = Number(goodTotalMoney); //订单总金额
      }
      const {
        invoice,
      } = this.submitInvoiceInfo
      const {
        invoiceType, // 发票系统返回的发票类型：0-增值税；1-普税
        invoiceTitle, //发票抬头/单位名称
        taxId, // 纳税人识别号
        invoiceAddress, //注册地址
        tel, //注册电话
        accountBankC, //开户银行
        accountBankNo, //银行账户
        invoiceCustomerCode, //开票客户代码
        invoiceIftId, //发票id
      } = invoice
      const invoiceFlag = !invoiceType || (invoiceType && invoiceType == -1) ? 10 : 20 // 是否选择开发票：10-不开发票；20-开发票
      const curInvoice = {
        invoiceTitle: invoiceTitle,
        taxpayerIdentifyNum: taxId,
        registerAddress: invoiceAddress,
        registerPhone: tel,
        openBank: accountBankC,
        bankAccount: accountBankNo,
        crmInvoiceId: invoiceCustomerCode,
        defInvoiceCode: invoiceIftId,
      }
      if (invoiceType == 1) { // 发票类型：10-增值税；20-普税
        curInvoice.invoiceType = 20
      } else if (invoiceType == 0) {
        curInvoice.invoiceType = 10
      }
      const {
        warehouseCode,
      } = this.vuex_cityInfo

      let address = {}
      let mayArrivedDay = ''
      let wannaArrivedAtBegin = ''
      let wannaArrivedAtEnd = ''
      let submitOrderStr = ''
      const nbsp = ' '
      const {
        selfAddressModel,
      } = this.selfAddressModelObj || {}
      if (deliverWay == 'zt') {
        const {
          mobile,
          receiverName,
          selfTakeTimeObj,
        } = this.selfAddressModelObj
        address = selfAddressModel
        if (address) {
          address.addressPersonList = [
            {
              mobile,
              receiverName
            }
          ]
        }
        if (selfTakeTimeObj && Object.keys(selfTakeTimeObj).length > 0) {
          const { year, month, day, selfTakeTime } = selfTakeTimeObj
          // 没有返回上午下午情况默认传18:00:00
          submitOrderStr = `${year}-${month}-${day} ${selfTakeTime || '18:00:00'}`
        }
      } else {
        //物流配送时间组装
        address = this.shippingAddressModel
        const lastTime = (this.orderInfo.deliverWayText.substring(this.orderInfo.deliverWayText.indexOf('2')))
        mayArrivedDay = lastTime.substring(0, 10)
        wannaArrivedAtBegin = mayArrivedDay + (lastTime.substring(10)).substring(0, lastTime.substring(10).indexOf('-')) + ':00'
        wannaArrivedAtEnd = mayArrivedDay + nbsp + (lastTime.substring(10)).substring((lastTime.substring(10)).indexOf('-') + 1) + ':00'
      }
      const {
        products,
        skuTotalNum,
        goodTotalWeight
      } = this.orderData
      // console.log('提交的数据', products)
      const params = {
        'address': address,
        'couponCode': couponChoosen ? couponChoosen.couponCode || '' : '',
        'usedCoupon': (couponChoosen && couponChoosen.couponCode) ? 10 : 20, // 使用优惠券 10-使用 20-未使用
        'deliverWay': deliverWay,
        'deliveryTimeType': 0, // 暂时默认传0
        'fileCopies': qualificationNum, //资质份数
        'finalTotalAmount': finalTotalAmount,
        'freight': originFreight,
        'goodTotalNum': skuTotalNum,
        'goodTotalWeight': goodTotalWeight,
        'goodTotalMoney': goodTotalMoney,
        'invoice': curInvoice,
        'invoiceFlag': invoiceFlag,
        'ip': '',
        'originalFile': needRedChapter,
        'payModel': payModelChoosen,
        'payMoney': payTotalMoney,
        'qualityFileRequired': needQualificationChoosen, // 是否需要资质: 10-需要; 20-不需求
        'remarks': orderRemark, // 订单备注
        'selfTakeTime': submitOrderStr,
        'selfTakeHour': selfAddressModel ? selfAddressModel.selfTakeHour : 0,
        'selfTakeType': selfAddressModel ? selfAddressModel.selfTakeType : 0,
        'separateShippingFee': freightType, // 运费类型：10-单开；20-分摊
        'shippingRemarksType': sendType, // 发货备注类型（发货方式 sendType）【0:货齐再发，1:有货先发】
        'skuModelList': products,
        'wannaArrivedAtBegin': wannaArrivedAtBegin, //期望送达时间开始时间
        'wannaArrivedAtEnd': wannaArrivedAtEnd, //期望送达时间结束时间
        'mayArrivedDay': mayArrivedDay,
        'wannaArrivedTimeBy': 20, //期望时间的选择：10-系统默认；20-用户选择 [字段不用了，默认传20]
        'warehouse_code': warehouseCode,
      }
      return params
    },
    /*提交订单*/
    async submitOrderFn() {
      this.modalOptions.custom.continueBuyingHandleType = 'submit'
      if (this.vuex_loginStatus && this.vuex_accountInfo && this.vuex_accountInfo.loginAccount) {
        if (this.validateAddress()) return // 物流配送 - 配送方式校验
        if (this.validateZtStoreInfo()) return // 门店自提 - 自提信息cell校验
        /*判断当前账号是否是有效账号*/
        const memeberStatus = await checkMemeberStatusFn({ loginAccount: this.vuex_accountInfo.loginAccount })
        if (!memeberStatus) {
          this.returnLoginFn()
          return
        }
        const params = this.makeConfirmOrderParamsFn()
        if (params.deliverWay == '') {
          this.$u.toast('请选择配送方式,此单只支持门店自提')
          return
        }
        if (params.deliverWay == 'zt' && !params.address) {
          this.$u.toast('请选择配送方式')
          return
        }
        submitOrder(params).then((res) => {
          const continueBuyingMethod = () => {
            const params = {
              order_id: res?.orderId,
              creatTime: res?.orderCreatedTime,
              paid_amount: this.priceInfo.payTotalMoney,
              payTime: 5
            }
            if (res?.orderId) {
              if (res.payType == '1001') {
                params.payType = 1001
                uni.redirectTo({
                  url: `/payments/cashier/index?params=${JSON.stringify(params)}` //todo 跳转收银台
                })
              } else {
                params.payType = 1301
                uni.redirectTo({
                  url: `/payments/transfer/index?params=${JSON.stringify(params)}`, //todo 跳转确认汇款
                })
              }
            } else {
              //this.$u.toast('单据异常: 订单号为空')
            }
          }
          if (Number(res.code) == 0) {
            continueBuyingMethod()
            /*const params = {
              order_id: res.orderId,
              creatTime: res.orderCreatedTime,
              paid_amount: this.priceInfo.payTotalMoney,
              payTime: 5
            }
            if (res.payType == '1001') {
              params.payType = 1001
              uni.redirectTo({
                url: `/payments/cashier/index?params=${JSON.stringify(params)}` //todo 跳转收银台
              })
            } else {
              params.payType = 1301
              uni.redirectTo({
                url: `/payments/transfer/index?params=${JSON.stringify(params)}`, //todo 跳转确认汇款
              })
            }*/
          } else if (Number(res.code) == 61) {
            if (res.abnormalProductList && res.abnormalProductList.length > 0) {
              this.modalOptions.custom.continueBuyingMethod = continueBuyingMethod
              this.abnormalModalFn(this.orderData.products, res.abnormalProductList, res.code)
            }
          } else {
            this.$u.toast(res.msg ? res.msg : '单据异常')
          }
        })
      } else {
        this.returnLoginFn()
      }
    },
    /*模态提示框确认*/
    modalConfirmFn(res) {
      if (res.confirmOperation == 'changCartProduct') { //购物车无货商品取消勾选
        this.changCartProduct()
      }
      if (res.confirmOperation == 'updatePrice') { //更新商品 详情已经更新，无需处理
        /*console.log(this.shoppingCartList);
        if (skuList && skuList.length > 0) {
          console.log(this.shoppingCartList);
          return
        }
        this.getShoppingCartListFn()*/
      }
      if (res.confirmOperation == 'updateAddress') { //更换地址
        this.editAddressFn()
      }
      if (res.confirmOperation == 'continueBuying') { //继续购买
        if (this.modalOptions.custom.continueBuyingHandleType == 'submit') {
          this.modalOptions.custom.continueBuyingMethod()
        }
      }
      if (res.confirmOperation == 'selectStore') { // 修改自提地点
        this.showPopFn({
          customParams: {
            popPage: 'selectStore'
          }
        })
      }
      this.modalOptions.modalShow = false
    },
    /*模态提示框返回*/
    modalCancelFn(res) {
      this.modalOptions.modalShow = false
      if (res.cancelOperation == 'backPurchaseOrder') {
        this.backPurchaseFn()
      }
      if (res.cancelOperation == 'changCartProduct') { //购物车无货商品取消勾选
        this.changCartProduct()
      }
      if (res.cancelOperation == 'changeDeliverWay') { //更换配送方式
        this.popContent = 'deliverWay'
        this.popShow = true
      }
    },
    /*信息列表方法执行*/
    handelCellMethod(methodName, val) {
      // console.log('handelCellMethod :>> ', methodName);
      // console.log('handelCellMethod :>> ', val);
      this[methodName](val)
    },
    /*pop打开*/
    showPopFn(obj) {
      this.popContent = obj.customParams.popPage
      this.popShow = true
    },
    /*pop关闭*/
    close() {
      this.popContent = ''
      this.popShow = false
    },
    /*获取定位经纬度*/
    getLocationFn() {
      return new Promise((resolve, reject) => {
        uni.getLocation({
          // #ifdef MP-WEIXIN
          type: 'gcj02',
          // #endif
          success: (res) => {
            this.settleParams.curLat = res.latitude
            this.settleParams.curLng = res.longitude
            resolve()
          },
          fail: function() {
            reject()
          }
        });
      })
    },
    /**
     * 切换提取方式
     * @param {*} item 当前选中的tab信息item
     */
    handleSwitchPackWay(item) {
      this.topTabs.current = item.key === 'logistics' ? 0 : 1
      const deliverWay = this.isLogistics ? (this.tempDeliverWay ?? '') : 'zt'
      this.orderInfo.deliverWay = deliverWay
      this.settleParams.deliverWay = deliverWay
      if (deliverWay == 'zt') {
        this.selfAddressSelectFn(10)
      } else {
        this.initTimeChangTab = true
        this.initTime = true
        this.deliverWayChangeFn(deliverWay, true)
      }
    },
    // 设置自提信息
    getZtStoreInfo(selfAddressModelObj) {
      const {
        receiverName,
        mobile,
        selfAddressModel
      } = selfAddressModelObj
      const nearestSite = this.getNearestZtStore(selfAddressModelObj)
      const initState = this.ztStore.initState
      const ztInfo = {
        addAlias: initState ? nearestSite?.add_alias : selfAddressModel?.add_alias,
        mobile: mobile ?? '',
        receiverName: receiverName ?? '',
        location: {
          latitude: initState ? nearestSite?.lat : selfAddressModel?.lat,
          longitude: initState ? nearestSite?.lng : selfAddressModel?.lng
        }
      }
      if (initState) {
        this.settleParams.selfAddressModel = nearestSite
        this.selfAddressModelObj.selfAddressModel = nearestSite
      }
      if (!this.isLogistics) {
        this.ztStore.initState = false // 为自提门店时，初始状态执行一次后便置为false
      }
      return ztInfo
    },
    // 获取最近自提点
    getNearestZtStore(selfAddressModelObj) {
      const { selfTakeAddressList, selfAddressModel } = selfAddressModelObj
      if (selfTakeAddressList) {
        const nearestSite = selfTakeAddressList.find(item => item.isLastAddress)
        return nearestSite
      }
      return selfAddressModel
    },
    // 查看地图
    handleViewMap() {
      const params = {
        ztStoreInfo: this.selfAddressModelObj.selfAddressModel, points: this.polylinePoints
      }
      uni.navigateTo({
        url: `/preview-map/index?params=${JSON.stringify(params)}`
      })
    },
    // 更新自提时间
    updateZtTime(info) {
      if (info) {
        this.selfAddressModelObj.selfTakeTimeObj = info
        this.$set(this.selfAddressModelObj.selfAddressModel, 'selfTakeHour', info.selfRequested ? parseInt(info.selfRequested, 10) : 0)
        
        let submitOrderStr = ''
        if (info && Object.keys(info).length > 0) {
          const { year, month, day, selfTakeTime } = info
          // 没有返回上午下午情况默认传18:00:00
          submitOrderStr = `${year}-${month}-${day} ${selfTakeTime || '18:00:00'}`
          this.$set(this.selfAddressModelObj.selfAddressModel, 'selfTakeTime', submitOrderStr)
        }
      }
      const { label = '' } = this.selfAddressModelObj.selfTakeTimeObj
      this.$set(this.ztInfo, 'selfTakeTime', label)
    },
    // 更新自提人地址
    updateAddressPersonList() {
      if (!this.settleParams?.selfAddressModel) return
      this.selfAddressModelObj.mobile = this.ztInfo?.mobile ?? ''
      this.selfAddressModelObj.receiverName = this.ztInfo?.receiverName ?? ''
      this.settleParams.selfAddressModel.addressPersonList = [{
        receiverName: this.ztInfo?.receiverName ?? '',
        mobile: this.ztInfo?.mobile ?? ''
      }]
    },
    // 物流配送 - 配送方式禁用项
    disableDeliverWayCell(address) {
      const index = this.orderCellColumn.findIndex(item => item.fields == 'deliverWayText')
      if (!address || Object.keys(address) == 0) {
        this.orderCellColumn[index].methodName = 'validateAddress'
      } else {
        this.orderCellColumn[index].methodName = 'showPopFn'
      }
    },
    // 校验收货地址是否为空
    validateAddress() {
      const hasNoAddress = !this.shippingAddressModel || Object.keys(this.shippingAddressModel).length == 0
      if (hasNoAddress && this.isLogistics) {
        this.$u.toast('请添加收货地址！')
        return true
      }
      return false
    },
    // 自提信息cell禁用项
    disableZtCell() {
      const disableList = ['addAlias', 'selfTakeTime']
      disableList.forEach(fields => {
        const cellIndex = this.ztCellColumn.findIndex(item => item.fields[0] == fields)
        if (cellIndex !== -1) {
          this.ztCellColumn[cellIndex].methodName = ''
          this.ztCellColumn[cellIndex].showRightIcon = false
          this.ztCellColumn[cellIndex].contentStyle = 'margin-right: 28rpx'
        }
      })
    },
    // 自提时间是否禁用
    changeUseStateZtTime(disabled) {
      if (this.ztStore.orderId) return // 智慧屏进入不执行操作
      if (disabled) {
        this.ztCellColumn[1].methodName = ''
        this.ztCellColumn[1].showRightIcon = false
        this.ztCellColumn[1].contentStyle = 'margin-right: 28rpx'
      } else {
        this.ztCellColumn[1].methodName = 'showPopFn'
        this.ztCellColumn[1].showRightIcon = true
        this.ztCellColumn[1].contentStyle = ''
      }
    },
    // 自提信息非空校验
    validateZtStoreInfo() {
      if (this.isLogistics) return false
      const { addAlias, selfTakeTime, receiverName, mobile } = this.ztInfo
      if (!addAlias) {
        this.$u.toast('请输入自提门店')
        return true
      }
      if (!selfTakeTime) {
        this.$u.toast('请输入自提时间')
        return true
      }
      if (!receiverName) {
        this.$u.toast('请输入提货人姓名')
        return true
      }
      if (!mobile) {
        this.$u.toast('请输入提货人电话')
        return true
      }
    },
    // 执行小程序扫码结果
    executeMiniScanResult(orderId) {
      return this.initConfigByScan(orderId)
    },
    // 执行微信扫码结果
    executeWeinXinScanResult(result) {
      const url = decodeURIComponent(result)
      const matchResult = url.match(/linkApp|orderId/g)
      const matchState = ['linkApp', 'orderId'].every(res => matchResult.includes(res))
      if (!matchState) return
      const params = url.split('?').pop()
      const { orderId } = qs.parse(params) ?? {}
      return this.initConfigByScan(orderId)
    },
    // 初始化扫码配置
    initConfigByScan(orderId) {
      if (!this.vuex_loginStatus) {
        this.returnLoginFn({ orderId })
        return false
      }
      this.ztStore.orderId = orderId
      this.topTabs.current = 1 // 默认选中门店自提
      this.disableZtCell()
      return true
    },
    //支付方式选择操作
    changePayment(changePayType) {
      this.orderInfo.payModelList.forEach((item) => {
        if (changePayType == item.payType) {
          this.orderInfo.payModelChoosen = item
          this.orderInfo.payName = item.payName
          this.orderInfo.payType = item.payType
          this.isClick = changePayType
        }
      })
      this.settleParams.payModelChoosen = this.orderInfo.payModelChoosen
      console.log('当前选择的支付方式', this.orderInfo.payModelChoosen, this.settleParams.payModelChoosen)
      console.log(this.orderInfo)
    }
  }
}
</script>

<style scoped lang="scss">
.order-payment-con{
  padding-top:10rpx;
  padding-bottom:238rpx;
  .list-sku{
    position: relative;
    padding-top: 20rpx;
    .company{
      padding:20rpx 0 30rpx 64rpx;
      background:url("../../static/image/shop.png") no-repeat 24rpx 20rpx/30rpx auto;
      height: 30rpx;
    }
    .editor-box{
      position: absolute;
      text-align: right;
      color:$uni-orange;
      right:20rpx;
      top:20rpx;
    }
  }
  .list-paymethod{
    display: flex;
    justify-content:space-between;
    padding: 24rpx;
    .online-payment{
      width: 318rpx;
      height: 148rpx;
      background: #f6f6f6;
      position: relative;
      box-sizing: border-box;
      display: flex;
      flex-direction: column;
      border-radius:$uni-border-radius-default;
      overflow: hidden;
      padding:16rpx 24rpx 16rpx 88rpx;
      .font_family{
        font-size: 48rpx;
        position: absolute;
        top:16rpx;
        left: 24rpx;
      }
      .nav{
        font-size:$uni-font-size-base;
        font-weight: bold;
      }
      .hint{
        font-size: $uni-font-size-sm;
        color: $uni-text-color-tips;
        margin-top: 8rpx;
      }
    }
    .online-payment-curr{
      border: 2rpx solid $uni-orange;
      .nav,.hint,.font_family{
        color: $uni-text-color-orange;
      }
    }
  }
  .list-title{
    border-bottom: 2rpx solid $uni-f5bg-color;
  }
  .tel-sale-bottom {
    position: fixed;
    bottom:170rpx;
    height: 68rpx;
    width: 100%;
    .tel-sale-btn{
      width:710rpx;
      height:68rpx;
      margin: 0 auto;
      line-height: 68rpx;
      border-radius:8px;
      border: 0!important;
      font-size:$uni-font-size-base;
      color:$uni-text-color-inverse!important;
      background: #474747;
    }
    .tel-icon{
      background:url("../../static/image/tel-sale.png") no-repeat 0 0/100%;
      width: 24rpx;
      height: 26rpx;
      position: relative;
      margin-right:6rpx;
      top:2rpx;
    }
  }
  .error-tips{
    float: right;
    padding: 10rpx 0;
    color: $uni-color-error;
  }
  .share{
    background:url("../../static/image/share.png") no-repeat 0 0/40rpx auto;
    width: 40rpx;
    height: 40rpx;
    float: left;
    margin: 32rpx 0 0 24rpx;
    border: #fff;
  }
  .order-price{
    float: left;
    color: $uni-grey-666;
    font-size: $uni-font-size-sm;
    .price{
      font-size:$uni-font-size-lg;
      font-weight: bold;
    }
  }
  .sticky-bottom{
    height: 80rpx;
    line-height: 80rpx;
    .sticky-btn{
      float: right;
      margin:14rpx 0 0 58rpx;
    }
  }
  .btn-orange{
    width: 160rpx;
    height: 56rpx;
    padding: 0!important;
    line-height: 56rpx;
  }
  .disabled-btn{
    background: $uni-text-color-disable;
  }
  .font-size-color {
    margin-right: 10rpx;
  }
  /deep/.uni-list-item__container{
    padding-top: 12rpx!important;
    padding-bottom: 12rpx!important;
  }
}
.map-box{
  margin-bottom: -60rpx;
}
</style>
